<?php

namespace App\Services;

use App\Models\AgentConfig;
use DateTime;
use Illuminate\Support\Arr;

final class ChargeContext
{
    private $charge;

    /**
     * @param $agentId
     */
    public function initInstance($agentId)
    {
        $config = AgentConfig::query()->where('agent_id', $agentId)->pluck('config_value', 'config_key');

        // 未配置支付通道默认使用易宝
        $payChannel = Arr::get($config, AgentConfig::PAY_CHANNEL, '');
        if ('adapay' == $payChannel) {
            $this->charge = new AdaPayService($config);
        } elseif ('sdpay' == $payChannel) {
            $this->charge = new SdPayService($config);
        } else {
            $this->charge = new YeepayService();
        }
    }

    /**
     * 获取支付链接.
     *
     * @param $orderNo
     * @param $amount
     * @param $goodsName
     * @param $userNo
     * @param $walletUserNo
     * @param $redirectUrl
     * @param mixed $extra
     *
     * @return mixed
     */
    public function getUnionPayLink($orderNo, $amount, $goodsName, $userNo, $walletUserNo, $redirectUrl, DateTime $expireTime, $extra = [])
    {
        return $this->charge->getUnionPayLink(
            $orderNo,
            $amount,
            $goodsName,
            $userNo,
            $walletUserNo,
            $redirectUrl,
            $expireTime,
            $extra
        );
    }

    public function queryOrder($orderId)
    {
        return $this->charge->queryOrder($orderId);
    }

    public function closeOrder($orderId, $uniqueOrderNo)
    {
        return $this->charge->closeOrder($orderId, $uniqueOrderNo);
    }
}
